package dataProces;

import java.sql.*;

public class DatabaseConnection {
    private Statement statement = null;
    private ResultSet rSet = null;
    private Connection connection = null;
    FileOperations fOperations = new FileOperations();

    public void mysqlConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/sys?useUnicode=true&characterEncoding=UTF-8";
            connection = DriverManager.getConnection(url, "root", "123456");
            statement = connection.createStatement();
        } catch (Exception e) {
            fOperations.logFile("数据库连接异常:" + e.getMessage());
        }
    }

    public boolean mysqlUpdate(String sql) {
        boolean update = true;
        try {
            fOperations.logFile("数据库操作语句:" + sql);
            statement.execute(sql);
        } catch (SQLException e) {
            update = false;
            fOperations.logFile("数据库操作异常:" + e.getMessage());
        }
        return update;
    }

    public ResultSet mysqlQuery(String sql) {
        try {
            fOperations.logFile("数据库查询语句:" + sql);
            rSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            fOperations.logFile("数据库查询异常:" + e.getMessage());
        }
        return rSet;
    }

    public void mysqlClose() {
        try {
            if (this.statement != null)
                statement.close();
            connection.close();
        } catch (SQLException e) {
            fOperations.logFile("数据库释放异常:" + e.getMessage());
        }
    }
}
